package com.shwread.android.qysw.activity.healthy;

import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.shwread.android.qysw.step.HealthyConfig;
import com.shwread.android.qysw.step.UserStepModel;
import com.shwread.android.qysw.step.adapter.RankAdapter;
import com.shwread.android.qysw.step.api.GetPhotoAsynctask;
import com.shwread.android.qysw.step.api.MyAsynctask;
import com.shwread.android.qysw.step.dto.HMRank;
import com.shwread.android.qysw.step.dto.HMRankDto;
import com.shwread.android.qysw.step.model.UserHealthyModel;
import com.shwread.android.qysw.step.view.LoadMoreListView;
import com.shwread.android.qysw.step.view.RectImageView;
import com.shwread.android.qysw.tools.BitmapUtil;
import com.shwread.android.qysw.tools.FileUtils;
import com.shwread.android.qysw.tools.ShareHelper;
import com.shwread.android.qysw10000136.R;
import com.squareup.picasso.Picasso;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.wechat.friends.Wechat;
import cn.sharesdk.wechat.moments.WechatMoments;
import logic.constants.AppConfig;

/**
 * Created by Fantasy on 16/3/27.
 */
public class HealthyRankActivity extends Activity {
    @InjectView(R.id.back_btn)
    ImageView backBtn;
    @InjectView(R.id.back_text)
    TextView backText;
    @InjectView(R.id.title_text)
    TextView titleText;
    @InjectView(R.id.right_text)
    TextView rightText;
    @InjectView(R.id.right_img)
    ImageView rightImg;
    @InjectView(R.id.head_icon_img)
    RectImageView headIconImg;
    @InjectView(R.id.name_text)
    TextView nameText;
    @InjectView(R.id.the_number_text)
    TextView theNumberText;
    @InjectView(R.id.step_count_text)
    TextView stepCountText;
    @InjectView(R.id.rank_list_view)
    LoadMoreListView rankListView;
    @InjectView(R.id.wechat_layout)
    RelativeLayout wechatLayout;
    @InjectView(R.id.cancle_layout)
    RelativeLayout cancleLayout;
    @InjectView(R.id.share_layout)
    RelativeLayout shareLayout;
    private LinearLayoutManager linearLayoutManager;
    RankAdapter rankAdapter;
    String myUrl;
    HashMap<String, String> params;
    private boolean isHasMore = true;
    private int mPage = 1;
    private List<Object> mRankList;
    HMRankDto hmRankDto;
    String myHeadUrl = "";
    private boolean isLoading = false;
    ShareHelper.ShareParams shareParams;
    File file;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.healthy_rank_activity);
        ButterKnife.inject(this);
        setView();

        linearLayoutManager = new LinearLayoutManager(this);
        rankListView.setLayoutManager(linearLayoutManager);
        mRankList = new ArrayList<>();
        rankAdapter = new RankAdapter(HealthyRankActivity.this);
        rankAdapter.init_data_list(mRankList);
        rankListView.setLoadMoreListViewAdapter(rankAdapter);
        ShareSDK.initSDK(this);
        rankListView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);

                int lastVisibleItem = linearLayoutManager.findLastVisibleItemPosition();
                int totalItemCount = linearLayoutManager.getItemCount();
                Log.i("darren", "totalItemCount:" + totalItemCount);
                if (lastVisibleItem >= totalItemCount - 4 && dy >= 0 && isHasMore) {
                    refreshData(mPage);
                } else if (mRankList.size() < 4 && isHasMore) {
                    refreshData(mPage);
                }
            }
        });
        isLoading = false;
        upDateHealthyInfo();


    }


    public void upDateHealthyInfo() {
        DecimalFormat df = new DecimalFormat("#0.0");
        String h_url = "hzlqswserver/health/updateHealthInfo";
        HashMap<String, String> hashMapUrl = new HashMap<>();
        hashMapUrl.put("url", h_url);
        HashMap<String, String> h_params = new HashMap<>();
        h_params.put("userId", UserHealthyModel.getInstance().getMyHmUserInfo().getUserId() + "");
        h_params.put("enterpriseId", AppConfig.getEnterpriseId());
        h_params.put("todayStep", UserStepModel.getInstance().getUserTodayStep() + "");
        h_params.put("todayMileage", df.format(UserStepModel.getInstance().getUserTodayDistance()));
        h_params.put("todayCalorie", df.format(UserStepModel.getInstance().getUserTodayCalories()));
        h_params.put("dailyStep", "5200");
        MyAsynctask myAsynctaskUpdate = new MyAsynctask(this, new MyAsynctask.RequestListener() {
            @Override
            public void requestSuccess(String result) {
                refreshData(1);
            }
        });
        myAsynctaskUpdate.execute(hashMapUrl, h_params);


    }

    public void refreshData(int page) {
        if (!isLoading) {
            isLoading = true;
            myUrl = "hzlqswserver/health/rank";
            HashMap<String, String> hashMapUrl = new HashMap<>();
            hashMapUrl.put("url", myUrl);
            params = new HashMap<>();
            params.put("userId", UserHealthyModel.getInstance().getMyHmUserInfo().getUserId() + "");
            params.put("enterpriseId", AppConfig.getEnterpriseId());
            params.put("page", page + "");
            params.put("pageSize", HealthyConfig.loadPageCount + "");
            MyAsynctask myAsynctask = new MyAsynctask(this, new MyAsynctask.RequestListener() {
                @Override
                public void requestSuccess(String result) {
                    JSONObject jsonObject = null;
                    try {
                        jsonObject = new JSONObject(result);
                        String res = jsonObject.optString("returnObject");
                        Log.i("darren2", res);
                        hmRankDto = HMRankDto.parserJson(res);
                        if (mPage == 1) {
                            HMRank hmRank = hmRankDto.getHMMyInfo();
                            nameText.setText(hmRank.getNickName());
                            theNumberText.setText("第" + hmRank.getSort() + "名");
                            stepCountText.setText(hmRank.getStep() + "");
                            if (!TextUtils.isEmpty(hmRank.getUserHead())) {
                                Picasso.with(HealthyRankActivity.this).load(hmRank.getUserHead()).into(headIconImg);
                                myHeadUrl = hmRank.getUserHead();
                            }
                        }
                        List<HMRank> hmRankList = hmRankDto.getData_list();
                        for (int i = 0; i < hmRankList.size(); i++) {
                            Log.i("darren", hmRankList.get(i).getNickName());
                        }
                        mRankList.addAll(hmRankList);
                        rankAdapter.setTotal_data_list(mRankList);
                        rankAdapter.notifyDataSetChanged();
                        Log.i("darren", "size:----->" + hmRankDto.getData_list().size());
                        if (hmRankDto.getData_list().size() == HealthyConfig.loadPageCount) {
                            isHasMore = true;
                            mPage += 1;
                        } else {
                            isHasMore = false;
                        }
                        rankAdapter.setIsHasMore(isHasMore);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    isLoading = false;
                }
            });
            myAsynctask.execute(hashMapUrl, params);
        }
    }

    public void setView() {
        titleText.setText("排行榜");
        backBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        rightText.setText("分享");
        rightText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                shareLayout.setVisibility(View.VISIBLE);
            }
        });
        cancleLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                shareLayout.setVisibility(View.INVISIBLE);
            }
        });
        shareLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                shareLayout.setVisibility(View.INVISIBLE);
                Platform platform = ShareSDK.getPlatform(Wechat.NAME);
                if (true == platform.isClientValid()) {
                    shareParams = new ShareHelper.ShareParams();
                    //file = new File(FileUtils.getImagePath(HealthyRankActivity.this, "icon" + ".jpg"));
                    GetPhotoAsynctask getPhotoAsynctask = new GetPhotoAsynctask(HealthyRankActivity.this, new GetPhotoAsynctask.RequestListener() {
                        @Override
                        public void requestSuccess(Bitmap result) {
                            BitmapUtil.saveBitmap(result, file);
                            file = new File(FileUtils.getImagePath(HealthyRankActivity.this, "icon" + ".jpg"));
                            shareParams.setImagePath(file.getAbsolutePath());
                            int step = UserStepModel.getInstance().getUserTodayStep();
                            double cals = UserStepModel.getInstance().getUserTodayCalories();
                            double dis = UserStepModel.getInstance().getUserTodayCalories();
                            String img = myHeadUrl;
                            DecimalFormat df = new DecimalFormat("#0.0");
                            String url = "http://www.shwread.com/run/index.html?num=" + step + "&cal=" + df.format(cals) + "&img=" + img + "&km=" + df.format(dis);
                            shareParams.setText("我今天走了" + UserStepModel.getInstance().getUserTodayStep() + "步," + "超过了" + hmRankDto.getPercentage() + "用户");
                            shareParams.setTitle("我今天走了" + UserStepModel.getInstance().getUserTodayStep() + "步," + "超过了" + hmRankDto.getPercentage() + "用户");
                            shareParams.setShareUrl(url);
                            ShareHelper.share(HealthyRankActivity.this, WechatMoments.NAME, shareParams);
                        }
                    });
                    getPhotoAsynctask.execute(myHeadUrl);
                } else {
                    Toast.makeText(HealthyRankActivity.this, "您的设备未安装微信", Toast.LENGTH_SHORT).show();
                }
            }
        });
//        shareLayout.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                shareLayout.setVisibility(View.INVISIBLE);
//                Platform platform = ShareSDK.getPlatform(Wechat.NAME);
//                if (true == platform.isClientValid()) {
//                    shareParams = new ShareHelper.ShareParams();
//                    file = new File(FileUtils.getImagePath(HealthyRankActivity.this, "icon" + ".jpg"));
//                    BitmapUtil.saveBitmap(BitmapUtil.drawableToBitmap(HealthyRankActivity.this.getResources().getDrawable(R.drawable.ic_launcher)), file);
//                    shareParams.setImagePath(file.getAbsolutePath());
//                    int step = UserStepModel.getInstance().getUserTodayStep();
//                    double cals = UserStepModel.getInstance().getUserTodayCalories();
//                    double dis = UserStepModel.getInstance().getUserTodayCalories();
//                    String img = myHeadUrl;
//                    DecimalFormat df = new DecimalFormat("#0.0");
//                    String url = "http://www.shwread.com/run/index.html?num=" + step + "&cal=" + df.format(cals) + "&img=" + img + "&km=" + df.format(dis);
//                    shareParams.setText("我今天走了" + UserStepModel.getInstance().getUserTodayStep() + "步," + "超过了" + hmRankDto.getPercentage() + "用户");
//                    shareParams.setTitle("我今天走了" + UserStepModel.getInstance().getUserTodayStep() + "步," + "超过了" + hmRankDto.getPercentage() + "用户");
//                    shareParams.setShareUrl(url);
//                    ShareHelper.share(HealthyRankActivity.this, WechatMoments.NAME, shareParams);
//                } else {
//                    Toast.makeText(HealthyRankActivity.this, "您的设备未安装微信", Toast.LENGTH_SHORT).show();
//                }
//            }
//        });
    }
}
